import { messages, queryCurrencyPrecision, eventTrack } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import config from 'config'
import httpFetch from 'share/httpFetch'
import menuRoute from 'routes/menuRoute'
import paymentService  from 'containers/pay/pay-workbench/pay-workbench.service'
import { Form, Radio, Badge, Table, Pagination, message, Button, Alert, Modal, Select, Input, Popconfirm, Spin, Row, Col,
  Dropdown, Menu, Icon } from 'antd'
const DropdownButton = Dropdown.Button;
const Option = Select.Option;
const FormItem = Form.Item;
import ExportModal from 'components/template/export-modal/export-modal';
const { TextArea } = Input;
import baseService from 'share/base.service'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import moment from 'moment'
import SearchArea from 'components/search-area'
import ErrorModal from 'containers/pay/template/error-modal'
import CheckModal from 'containers/pay/template/check-modal'

class PayFail extends React.Component {
  constructor(props) {
    super(props);
    const userJobsDTOs = [];
    props.user.companyWithUserJobsDTOList.map(item => {
      item.userJobsDTOList.map(it => {
        userJobsDTOs.push(it);
      })
    });
    this.mainJob = userJobsDTOs.filter(item => item.companyMainPosition)[0];
    this.state = {
      radioValue: '',
      partnerId: undefined,
      buttonDisabled: true,
      selectFlag:null,
      payCompanyBankNumber:null,
      searchForm: [
        {
          type: 'list', isRequired: true,listType: 'permission_company',
          id: 'paymentCompanyId',
          defaultValue: props.tenantMode ? [{name: this.mainJob.companyName, id: this.mainJob.companyId}] : [{name: props.company.name, id: props.company.id}],
          label: messages('pay.key137')/*单据公司*/,
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams:{enabled: true}
        },
        {type: 'input', id: 'documentNumber', label: messages('pay.key13'/*单据编号*/)}, //单据编号
        {type: 'value_list', id: 'documentCategory', label: messages('pay.key14'/*单据类型*/), options: [], valueListCode: 2106}, //单据类型
        {
          type: 'list', listType: "select_authorization_user", options: [], id: 'employeeId', label: messages('pay.key15'/*申请人*/), labelKey: "userCode",
          valueKey: "userId", single: true
        }, //申请人
        {type: 'items', id: 'amountRange', items: [
          {type: 'input', id: 'amountFrom', label: messages('pay.key16'/*支付金额从*/)},
          {type: 'input', id: 'amountTo', label: messages('pay.key17'/*支付金额至*/)}
        ]},
        {
          type: 'items', id: 'partner', items: [
            {
              type: 'value_list',
              id: 'partnerCategory',
              label: messages('pay.key18')/*类型*/,
              valueListCode: 2107,
              options: [],
              event: 'code'
            },
            {
              type: 'list',
              id: 'partnerId',
              label: messages('pay.key19')/*收款方*/,
              listType: 'user',
              single: true,
              disabled: true,
              labelKey: 'fullName',
              valueKey: "id"
            },
          ]
        },
        {type: 'input', id: 'billcode', label: messages('pay.key20'/*付款流水号*/)},
        {type: 'input', id: 'customerBatchNo', label: messages('pay.key21'/*付款批次号*/)},
        {
          type: 'list', id: 'departmentOids', label: messages('financial-management.key195'/*部门*/),
          listType: 'department', labelKey: 'name', valueKey: 'departmentOid'
        }
      ],
      searchParams: { paymentCompanyId: props.tenantMode ? this.mainJob.companyId : props.company.id },
      columns: [
        {title: messages('pay.key20'/*付款流水号*/), dataIndex: 'billcode', render: (value, record) => <a onClick={() => {this.checkPaymentDetail(record)}}>{value}</a>},
        {title: messages('pay.key22'/*单据编号 | 单据类型*/), dataIndex: 'documentNumber', render: (value, record) => {
          return (
            <div>
              <a onClick={() => {this.checkPaymentDetail(record)}}>{value}</a>
              <span className="ant-divider"/>
              {record.documentTypeName}
            </div>
          )}
        },
        {title: messages('pay.key21'/*付款批次号*/), dataIndex: 'customerBatchNo'},
        {title: messages('pay.key23'/*工号 | 申请人*/), dataIndex: 'employeeName', render: (value, record) => {
          return (
            <div>
              {record.employeeId}
              <span className="ant-divider"/>
              {value}
            </div>
          )}
        },
        {title: messages('common.currency')/*币种*/, dataIndex: 'currency'},
        {title: messages('pay.key24'/*本次支付金额*/), dataIndex: 'amount', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currency))},
        {title: messages('pay.key25'/*付款方式*/), dataIndex: 'paymentTypeName'},
        {title: messages('pay.key26'/*类型 | 收款方*/), dataIndex: 'partnerCategoryName', render: (value, record) => {
          return (
            <div>
              {value}
              <span className="ant-divider"/>
              {record.partnerName}
            </div>
          )}
        },
        {title: messages('pay.key27'/*收款方账号*/), dataIndex: 'payeeAccountNumber'},
        {title: messages('common.column.status')/*状态*/, dataIndex: 'paymentStatusName', render: (state, record) => <Badge status='error' text={record.refundStatus === 'Y' ? messages('pay.key28'/*退票*/) : state}/>},
      ],
      selectedRowKeys: [], //选中行key
      selectedRows: [],  //选中行
      noticeAlert: null, //提示
      errorAlert: null,  //错误
      currency: null,    //选中行的币种
      modalVisible: false,
      modalLoading: false,
      payAccountFetching: false,
      payWayFetching: false,
      payAccountOptions: [],
      pageSizeOptions: ['10', '20', '30', '50'],

      /* 线上 */
      onlineLoading: false,
      onlineData: [],
      onlinePage: 0,
      onlinePageSize: 10,
      onlinePagination: {
        total: 0
      },
      onlineCash: [],  //总金额
      payWayOptions: [],

      /* 落地文件 */
      fileLoading: false,
      fileData: [],
      filePage: 0,
      filePageSize: 10,
      filePagination: {
        total: 0
      },
      storageKey: localStorage.getItem('EBANK_PAYMENT_PAY') || 'file',
      fileCash: [],  //总金额
      reimbursementBatchOID: '',
      searchCostCenterCommands: null,
      paymentDetail:  menuRoute.getRouteItem('payment-detail','key'),    //支付详情
      exportLoading: false,
      realPayCompanyId: '',
      radioOption: [],
      loading: false,
      isEBank: {},
      errorVisible: false,
      errorData: {}
    };
  }

  componentWillMount() {
    this.getList();
    this.getFinanceConfig();
  }

  getFinanceConfig = () => {
    let companyId = this.state.searchParams.paymentCompanyId;
    this.setState({ loading: true });
    Promise.all([
      baseService.getFinanceConfig({ companyId, itemGroupCode: 'PAYMENT_1_G1' }),
      baseService.getFinanceConfig({ companyId, itemGroupCode: 'PAYMENT_1_G2' })
    ]).then(res => {
      this.setState({
        loading: false,
        radioOption: this.props.orderTab(res[0].data),
        radioValue: res[1].data[0].itemCode
      });
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('pay.key225')/*系统异常*/);
    });
  };

  //获取列表及总金额
  getList = () => {
    let online = new Promise((resolve, reject) => {
      this.getOnlineList(resolve, reject)
    });
    let file = new Promise((resolve, reject) => {
      this.getFileList(resolve, reject)
    });
    Promise.all([ online, file ]).then(() => {
      this.getOnlineCash();
      this.getFileCash();
    }).catch(() => {
      message.error(messages('pay.key29'/*数据加载失败，请重试*/))
    })
  };

  //搜索
  search = (values) => {
    const { searchCostCenterCommands } = this.state;
    if(!!this.state.partnerId){
      values.partnerId=this.state.partnerId;
    }else {
      values.partnerId && values.partnerId.length>0 && (values.partnerId = values.partnerId[0].id)
    }
    if(searchCostCenterCommands){
      paymentService.getCostCenterId(searchCostCenterCommands).then(res => {
        values.costCenterItemOids = res.data;
        this.setState({
          searchParams: values,
          onlineCash: [],
          fileCash: []
        }, () => {
          this.getList()
        })
      }).catch(e => {
        message.error(e.response.data.message);
      })
    } else {
      this.setState({
        searchParams: values,
        onlineCash: [],
        fileCash: []
      }, () => {
        this.getList();
        this.getFinanceConfig();
      })
    }
  };

  //清除搜索内容
  clear = () => {
    this.setState({searchCostCenterCommands: null},() => {
      this.eventHandle('code', null, '1');
    });
  };

  eventHandle = (type, value, search) => {
    let { searchForm, partnerId } = this.state;
    if (type === 'code') {
      partnerId = undefined;
      value = value ? value : "";
      this.formRef.setValues({partnerId: undefined});
      if (value === "EMPLOYEE") {
        let item = searchForm[5];
        item.items[1].disabled = false;
        item.items[1].listType = 'user';
        item.items[1].labelKey = 'fullName';
        searchForm[5] = item;
      }
      if (value === "VENDER") {
        let item = searchForm[5];
        item.items[1].disabled = false;
        item.items[1].listType = 'finance_vendor';
        item.items[1].labelKey = 'venNickname';
        searchForm[5] = item;
      }
      if (value === "") {
        let item = searchForm[5];
        item.items[1].disabled = true;
        searchForm[5] = item;
      }
      this.setState({ searchForm, partnerId },() => {
        search === '1' && this.formRef.handleSearch();
      })
    }
  };

  //选择 线上／线下／落地文件
  onRadioChange = (e) => {
    this.setState({
      radioValue: e.target.value,
      selectedRowKeys: [],
      selectedRows: []
    }, () => {
      let values = this.props.form.getFieldsValue();
      Object.keys(values).map(key => {
        this.props.form.setFieldsValue({ [key]: undefined })
      });
      this.noticeAlert(this.state.selectedRows)
    })
  };

  //选择/取消选择某行的回调
  handleSelectRow = (record, selected) => {
    let selectedRows = this.state.selectedRows;
    if(selected) {
      selectedRows.push(record)
    } else {
      selectedRows.map((item, index) => {
        item.id === record.id && (selectedRows[index] = 0)
      });
      selectedRows.delete(0)
    }
    this.setState({ selectedRows }, () => {
      this.noticeAlert(this.state.selectedRows)
    })
  };

  //选中行的key
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys })
  };

  //选择/取消选择所有行的回调
  handleSelectAllRow = (selected, selectedRow, changeRows) => {
    let selectedRows = this.state.selectedRows;
    if(selected){
      changeRows.map(item => {
        selectedRows.push(item)
      })
    } else {
      selectedRows.map((row, index) => {
        changeRows.map(item => {
          row.id === item.id && (selectedRows[index] = 0)
        })
      });
      changeRows.map(() => {
        selectedRows.delete(0)
      })
    }
    this.setState({ selectedRows }, () => {
      this.noticeAlert(this.state.selectedRows)
    })
  };

  //提示框显示
  noticeAlert = (rows) => {
    let amount = 0;
    let errFlag = false;
    let currency = rows[0] ? rows[0].currency : null;
    let paymentCompanyId = rows[0] ? rows[0].paymentCompanyId : null;
    this.setState({ currency });
    rows.forEach(item => {
      if (item.currency === currency && item.paymentCompanyId === paymentCompanyId) {
        amount += item.amount
      } else {
        errFlag = true
      }
    });
    if (!errFlag) {
      let noticeAlert = (
        <span> {messages('pay.key30'/*已选择*/)}<span className='default-color-font' style={{fontWeight:'bold'}}> {rows.length} </span> {messages('pay.key31'/*项*/)}
          <span className="ant-divider" /> {messages('pay.key130',{arg1:currency}/*本次支付金额总计：{arg1}*/)} <span style={{fontWeight:'bold',fontSize:'15px'}}> {this.filterMoney(amount, queryCurrencyPrecision(currency), true)} </span>
        </span>
      );
      this.setState({
        noticeAlert: rows.length ? noticeAlert : null,
        errorAlert: null,
        buttonDisabled: !rows.length
      });
    } else {
      let errorAlert = (
        <span> {messages('pay.key30'/*已选择*/)}<span className='default-color-font' style={{fontWeight:'bold'}}> {rows.length} </span> {messages('pay.key31'/*项*/)}
          <span className="ant-divider" /> {messages('pay.key32'/*不同币种、不同付款机构不可同时支付*/)}
        </span>
      );
      this.setState({
        noticeAlert: null,
        errorAlert: errorAlert,
        buttonDisabled: true
      });
    }
  };

  //获取汇率
  getExchangeRate = () => {
    let currencyDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let url = `${config.baseUrl}/api/company/standard/currency/get?currency=${this.state.currency}&currencyDate=${currencyDate}`;
    httpFetch.get(url).then(res => {
      this.props.form.setFieldsValue({ exchangeRate: res.data.rate });
    }).catch(e => {
      message.error(messages('pay.key33'/*获取汇率失败！*/));
    })
  };

  //点击重新支付按钮
  repay = () => {
    this.setState({ payWayOptions: [], payAccountOptions: [], modalVisible: true,selectFlag:true,payCompanyBankNumber:null });
    let values = this.props.form.getFieldsValue();
    Object.keys(values).map(key => {
      this.props.form.setFieldsValue({ [key]: undefined });
    });
    this.props.form.setFieldsValue({ currency: this.state.currency });
    this.getExchangeRate();
  };

  //点击取消支付按钮
  cancelPay = () => {
    paymentService.cancelPay(this.state.selectedRows).then(res => {
      if (res.status === 200) {
        message.success(messages('pay.key34'/*取消支付成功*/));
        this.getList();
        this.setState({ selectedRows: [] }, () => {
          this.noticeAlert(this.state.selectedRows)
        })
      }
    }).catch(() => {
      message.error(messages('pay.key35'/*取消支付失败，请重试*/));
    })
  };

  //获取付款账户
  getPayAccount = () => {
    if (this.state.payAccountOptions.length > 0) return;
    this.setState({ payAccountFetching: true });
    const { selectedRows, searchParams } = this.state;
    let temp = selectedRows[0];
    let setOfBooksId = temp.setOfBooksId;
    let paymentMethodCode = temp.paymentMethodCategory;
    let currency = temp.currency;
    let url = `/api/CompanyBank/getAuthCompanyBank/${this.props.user.userOID}`;
    httpFetch.get(url, {
      setOfBooksId,
      paymentMethodCode,
      currency,
      companyId: searchParams.paymentCompanyId
    }).then(res => {
      res.status === 200 && this.setState({ payAccountOptions: res.data, payAccountFetching: false })
    }).catch(() => {
      this.setState({ payAccountFetching: false })
    })
  };

  //获取付款方式
  getPayWay = () => {
    const { radioValue,payCompanyBankNumber } = this.state;
    //if (this.state.payWayOptions.length > 0) return;
    this.setState({ payWayFetching: true });
    let url = `${config.baseUrl}/api/comapnyBankPayment/get/company/bank/payment/by/bank/account/number?number=${payCompanyBankNumber}&paymentMethod=${radioValue}`;
    httpFetch.get(url).then(res => {
      res.status === 200 && this.setState({ payWayOptions: res.data, payWayFetching: false })
    }).catch(() => {
      this.setState({ payWayFetching: false })
    })
  };

  //查看支付流水详情
  checkPaymentDetail = (record) => {
    this.context.router.push(this.state.paymentDetail.url.replace(':tab', 'Fail').replace(':id', record.id));
  };

  /*********************** 获取总金额 ***********************/

  //线上
  getOnlineCash = () => {
    paymentService.getAmount('ONLINE_PAYMENT', 'F', this.state.searchParams).then(res => {
      this.setState({ onlineCash: res.data })
    })
  };

  //落地文件
  getFileCash = () => {
    paymentService.getAmount('EBANK_PAYMENT', 'F', this.state.searchParams).then(res => {
      this.setState({ fileCash: res.data })
    })
  };

  /************************ 获取列表 ************************/

  //线上
  getOnlineList = (resolve, reject) => {
    const { onlinePage, onlinePageSize, searchParams } = this.state;
    this.setState({ onlineLoading: true });
    paymentService.getFailList(onlinePage, onlinePageSize, 'ONLINE_PAYMENT', searchParams).then(res => {
      if (res.status === 200) {
        this.setState({
          onlineData: res.data,
          onlineLoading: false,
          onlinePagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0
          }
        });
        resolve && resolve()
      }
    }).catch(() => {
      this.setState({ onlineLoading: false });
      reject && reject()
    })
  };

  //落地文件
  getFileList = (resolve, reject) => {
    const { filePage, filePageSize, searchParams } = this.state;
    this.setState({ fileLoading: true });
    paymentService.getFailList(filePage, filePageSize, 'EBANK_PAYMENT', searchParams).then(res => {
      if (res.status === 200) {
        this.setState({
          fileData: res.data,
          fileLoading: false,
          filePagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0
          }
        });
        resolve && resolve()
      }
    }).catch(() => {
      this.setState({ fileLoading: false });
      reject && reject()
    })
  };

  /********************* 修改每页显示数量 *********************/

  //线上
  onlinePaginationChange = (onlinePage, onlinePageSize) => {
    onlinePage = onlinePage - 1;
    this.setState({ onlinePage, onlinePageSize },() => {
      this.getOnlineList()
    })
  };

  //落地文件
  filePaginationChange = (filePage, filePageSize) => {
    filePage = filePage - 1;
    this.setState({ filePage, filePageSize },() => {
      this.getFileList()
    })
  };

  /********************** 弹框 - 确认支付 *********************/

  //线上
  handleOnlineModalOk = () => {
    const { realPayCompanyId, isEBank } = this.state, { user } = this.props;
    eventTrack({
      category: 'PAY_FAIL',
      action: 'ONLINE_PAYMENT',
      label: `公司=${this.mainJob.companyName}&操作人=${user.name}&操作时间=${new Date().format('yyyy-MM-dd hh:mm:ss')}`
    });
    let params = {};
    params.details = this.state.selectedRows;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.paymentMethodCategory = "ONLINE_PAYMENT";
        values.payCompanyBankName = isEBank.companyBank.bankAccountName;
        values.payCompanyBankNumber = values.payCompanyBankNumber.key;
        values.paymentDescription = values.paymentTypeId.label;
        values.paymentTypeId = values.paymentTypeId.key;
        values.realPayCompanyId = realPayCompanyId;
        params.payDTO = values;
        this.setState({ modalLoading: true });
        if (isEBank.bankPayInfo && isEBank.bankPayInfo.status === 'Y') {
          params.bankPayChannel = isEBank.bankPayInfo.vendor;
          paymentService.checkReEBank(params).then(res => {
            if (res.data.isSuccess) {
              let uKey = this.props.checkBrowser(res.data.requestSeqNo);
              if ( uKey ) {
                let tempParams = Object.assign(params, {
                  bankPayChannel: isEBank.bankPayInfo.vendor,
                  orderRequestNo: res.data.orderRequestNo,
                  data: {
                    requestSeqNo: res.data.orderRequestNo,
                    oper: uKey.certInfo.split('@')[1],
                    operSign: uKey.res
                  }
                });
                paymentService.createReOrder(tempParams).then(response => {
                  switch (response.data.batStatus) {
                    case '01':
                      message.error(response.data.message);
                      this.setState({ modalLoading: false });
                      return;
                    case '02':
                      Modal.confirm({
                        title: messages('pay.key234')/*重复风险警告*/,
                        content: messages('pay.key235')/*本次支付存在重复支付请求风险，是否继续支付？*/,
                        onOk: () => this.handleContinuePay(response.data),
                        onCancel: () => {this.setState({ modalLoading: false })}
                      });
                      return;
                    default:
                      message.success(messages('pay.key66')/*支付成功*/);
                      this.getOnlineList();
                      this.getOnlineCash();
                      this.setState({
                        modalVisible: false,
                        modalLoading: false,
                        selectedRowKeys: [],
                        selectedRows: []
                      },() => {
                        this.noticeAlert(this.state.selectedRows)
                      });
                      return;
                  }
                })
              } else {
                this.setState({ modalLoading: false })
              }
            } else {
              this.setState({ errorData: res.data },() => {
                this.setState({ errorVisible: true })
              });
            }
          }).catch(e => {
            message.error(e.response.data.message);
            this.setState({ modalLoading: false })
          })
        } else {
          paymentService.rePay(params).then(res => {
            if (res.status === 200) {
              message.success(messages('common.operate.success')/*操作成功*/);
              this.getOnlineList();
              this.getOnlineCash();
              this.setState({
                modalVisible: false,
                modalLoading: false,
                selectedRowKeys: [],
                selectedRows: []
              },() => {
                this.noticeAlert(this.state.selectedRows)
              })
            }
          }).catch(e => {
            message.error(messages('pay.key131',{arg1:e.response.data.message}/*操作失败，{arg1}*/));
            this.setState({ modalLoading: false })
          })
        }
      }
    })
  };

  handleContinuePay = data => {
    const { porderId, batchNo } = data;
    paymentService.continuePay({ porderId, batchNo }).then(res => {
      if (res.data) {
        message.success(messages('pay.key66')/*支付成功*/);
        this.getOnlineList();
        this.getOnlineCash();
        this.setState({
          modalVisible: false,
          modalLoading: false,
          selectedRowKeys: [],
          selectedRows: []
        },() => {
          this.noticeAlert(this.state.selectedRows)
        });
      }
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ modalLoading: false });
    });
  };

  handleCloseError = () => {
    this.setState({ errorVisible: false, modalVisible: false, modalLoading: false });
  };

  //落地文件
  handleFileModalOk = value => {
    const { storageKey, realPayCompanyId, isEBank } = this.state, { user } = this.props;
    eventTrack({
      category: 'PAY_FAIL',
      action: 'EBANK_PAYMENT',
      label: `公司=${this.mainJob.companyName}&操作人=${user.name}&操作时间=${new Date().format('yyyy-MM-dd hh:mm:ss')}`
    });
    let key = value.key || null;
    if(key && key !== storageKey) {
      localStorage.setItem('EBANK_PAYMENT_PAY', key);
      this.setState({storageKey: key});
    }
    let params = {};
    params.details = this.state.selectedRows;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.paymentMethodCategory = "ONLINE_PAYMENT";
        values.payCompanyBankName = isEBank.companyBank.bankAccountName;
        values.payCompanyBankNumber = values.payCompanyBankNumber.key;
        values.paymentDescription = values.paymentTypeId.label;
        values.paymentTypeId = values.paymentTypeId.key;
        values.realPayCompanyId = realPayCompanyId;
        params.payDTO = values;
        this.setState({ modalLoading: true, exportLoading: true });
        paymentService.rePayEBank(params).then(res => {
          if (res.status === 200) {
            this.setState({reimbursementBatchOID: res.data, exportLoading: false},() => {
              this.export.setInitState();
              this.getFileList();
              this.getFileCash();
              this.setState({
                modalVisible: false,
                modalLoading: false,
                selectedRowKeys: [],
                selectedRows: []
              }, () => {
                this.noticeAlert(this.state.selectedRows)
              })
            });
          }
        }).catch(e => {
          this.setState({modalLoading: false, exportLoading: false});
          message.error(messages('pay.key131',{arg1:e.response.data.message}/*操作失败，{arg1}*/));
        })
      }
    })
  };

  /************************ 内容渲染 ************************/

  //线上
  renderOnlineContent = () => {
    const { columns, onlineData, onlineLoading, onlinePageSize, onlinePagination, onlineCash, pageSizeOptions,
      selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.handleSelectRow,
      onSelectAll: this.handleSelectAllRow
    };
    const tableTitle = (
      <div> {messages('pay.key36'/*退票或失败*/)}
        {onlineCash.length > 0 && <span className="ant-divider"/>}
        {onlineCash.map((item, index) => {
          return (
            <div key={index} style={{display:'inline-block'}}> {messages('pay.key132',{arg1:item.currency}/*金额：{arg1}*/)} <span className="num-style">{this.filterMoney(item.totalAmount, queryCurrencyPrecision(item.currency), true)}</span>
              <span className="ant-divider"/> {messages('pay.key37'/*交易笔数：*/)}<span className="num-style">{item.documentNumber}{messages('pay.key38'/*笔*/)}</span>
              {index !== onlineCash.length - 1 && <span className="ant-divider"/>}
            </div>
          )
        })}
      </div>
    );
    return (
      <div className="fail-online">
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={onlineData}
               pagination={false}
               loading={onlineLoading}
               rowSelection={rowSelection}
               title={()=>{return tableTitle}}
               scroll={{x: true, y: false}}
               bordered
               size="middle"/>
        <Pagination size="small"
                    defaultPageSize={onlinePageSize}
                    showSizeChanger
                    pageSizeOptions={pageSizeOptions}
                    total={onlinePagination.total}
                    onChange={this.onlinePaginationChange}
                    onShowSizeChange={this.onlinePaginationChange}
                    style={{margin:'16px 0', textAlign:'right'}} />
      </div>
    )
  };

  //落地文件
  renderFileContent = () => {
    const { columns, fileData, fileLoading, filePageSize, filePagination, fileCash, pageSizeOptions } = this.state;
    const rowSelection = {
      onSelect: this.handleSelectRow,
      onSelectAll: this.handleSelectAllRow
    };
    const tableTitle = (
      <div> {messages('pay.key36'/*退票或失败*/)}
        {fileCash.length > 0 && <span className="ant-divider"/>}
        {fileCash.map((item, index) => {
          return (
            <div key={index} style={{display:'inline-block'}}> {messages('pay.key132',{arg1:item.currency}/*金额：{arg1}*/)} <span className="num-style">{this.filterMoney(item.totalAmount, queryCurrencyPrecision(item.currency), true)}</span>
              <span className="ant-divider"/> {messages('pay.key37'/*交易笔数：*/)}<span className="num-style">{item.documentNumber}{messages('pay.key38'/*笔*/)}</span>
              {index !== fileCash.length - 1 && <span className="ant-divider"/>}
            </div>
          )
        })}
      </div>
    );
    return (
      <div className="fail-file">
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={fileData}
               pagination={false}
               loading={fileLoading}
               rowSelection={rowSelection}
               title={()=>{return tableTitle}}
               scroll={{x: true, y: false}}
               bordered
               size="middle"/>
        <Pagination size="small"
                    defaultPageSize={filePageSize}
                    showSizeChanger
                    pageSizeOptions={pageSizeOptions}
                    total={filePagination.total}
                    onChange={this.filePaginationChange}
                    onShowSizeChange={this.filePaginationChange}
                    style={{margin:'16px 0', textAlign:'right'}} />
      </div>
    )
  };
  selectHandleChange = value => {
    const { payAccountOptions } = this.state;
    if (value.key) {
      let res = payAccountOptions.find(item => item.companyBank.bankAccountNumber === value.key);
      this.setState({
        selectFlag: false,
        payCompanyBankNumber: value.key,
        payWayOptions: [],
        realPayCompanyId: res.companyId,
        isEBank: res
      });
      this.props.form.setFieldsValue({ paymentTypeId: undefined });
    }
  };

  changeCostCenter = (value) => {
    this.setState({searchCostCenterCommands: value})
  };
  /************************* End *************************/

  render(){
    const { getFieldDecorator } = this.props.form;
    const { selectFlag,searchForm, radioValue, buttonDisabled, noticeAlert, errorAlert, modalVisible, modalLoading,
      currency, payWayOptions, payAccountFetching, payWayFetching, payAccountOptions, reimbursementBatchOID,
      searchCostCenterCommands, storageKey, exportLoading, loading, radioOption, errorVisible, errorData } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    const menu = (
      <Menu onClick={this.handleFileModalOk} style={{ maxHeight:250, overflow:'auto', width: '145px' }}>
        <Menu.Item key={'file'}>{messages('pay.key49')/*导出报盘文件*/}</Menu.Item>
        <Menu.Item key={'detail'}>{messages('pay.key220')/*导出报盘明细*/}</Menu.Item>
      </Menu>
    );
    return (
      <Spin className="pay-fail" spinning={loading}>
        <ExportModal
          exportTitle={''}
          exportType="REIMBURSEMENT_BATCH"
          disabled={!this.checkNewAuth()}
          exportCondition={{
            reimbursementBatchOID: reimbursementBatchOID
          }}
          wrappedComponentRef={(inst) => this.export = inst}
          exportCommand={storageKey === 'file' ? 'BATCH' : 'BATCH_DETAIL'}/>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
          eventHandle={this.eventHandle}
          wrappedComponentRef={(inst) => this.formRef = inst}
          extraFieldsIndex={9}
          extraFields={[
            <div>
              <div style={{lineHeight: '28px'}}> {messages('pay.key110')/*成本中心*/}
              </div>
              <CostCenterSearchForm title={messages('pay.key110')/*成本中心*/}
                                    type='id'
                                    value={searchCostCenterCommands}
                                    onChange={this.changeCostCenter}/>
            </div>
          ]}
        />
        <Radio.Group value={radioValue} style={{margin:'20px 0'}}
                     onChange={this.onRadioChange}>
          {
            radioOption.map(item => <Radio.Button value={item.itemCode}>{item.showName}</Radio.Button>)
          }
        </Radio.Group>
        <div style={{marginBottom:10}}>
          <Button type="primary"
                  disabled={buttonDisabled}
                  style={{marginRight:20}}
                  onClick={this.repay}>{messages('pay.key42'/*重新支付*/)}</Button>
          <Popconfirm title={messages('pay.key43'/*确定取消支付吗*/)} onConfirm={this.cancelPay}>
            <Button type="primary"
                    disabled={buttonDisabled}>{messages('pay.key44'/*取消支付*/)}</Button>
          </Popconfirm>
        </div>
        {noticeAlert ? <Alert message={noticeAlert} type="info" showIcon style={{marginBottom:'10px'}}/> : ''}
        {errorAlert ? <Alert message={errorAlert} type="error" showIcon style={{marginBottom:'10px'}}/> : ''}
        {radioValue === 'ONLINE_PAYMENT' && this.renderOnlineContent()}
        {radioValue === 'EBANK_PAYMENT' && this.renderFileContent()}
        {radioValue === 'ONLINE_PAYMENT' ? (
          <Modal title={messages('pay.key45'/*线上重新支付确认*/)}
                 visible={modalVisible}
                 confirmLoading={modalLoading}
                 okText={messages('pay.key46'/*确认支付*/)}
                 onOk={this.handleOnlineModalOk}
                 onCancel={() => this.setState({ modalVisible: false })}>
            <Form>
              <FormItem  {...formItemLayout} label={messages('pay.key47'/*付款账户*/)}>
                {getFieldDecorator('payCompanyBankNumber', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }]
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}
                          onFocus={this.getPayAccount}
                          notFoundContent={payAccountFetching ? <Spin size="small" /> : messages('pay.key6'/*无匹配结果*/)}
                          onChange={this.selectHandleChange}
                          labelInValue>
                    {payAccountOptions.map(option => {
                      return <Option key={option.companyBank.bankAccountNumber}>
                        {`${option.companyBank.bankAccountName} - ${option.companyBank.bankAccountNumber}`}
                        {option.bankPayInfo && option.bankPayInfo.status === 'Y' && (
                          <span style={{color: "#108ee9"}}>{messages('pay.key233')/*（银企直联生效中）*/}</span>
                        )}
                      </Option>
                    })}
                  </Select>
                )}
              </FormItem>
              <FormItem  {...formItemLayout} label={messages('common.currency')/*币种*/}>
                {getFieldDecorator('currency', {
                  rules: [{ required: true }]
                })(
                  <Input disabled />
                )}
              </FormItem>
              <FormItem  {...formItemLayout} label={messages('common.currency.rate')/*汇率*/}>
                {getFieldDecorator('exchangeRate', {
                  rules: [{
                    required: true
                  }]
                })(
                  <Input disabled />
                )}
              </FormItem>
              <FormItem  {...formItemLayout} label={messages('pay.key25'/*付款方式*/)}>
                {getFieldDecorator('paymentTypeId', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }]
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}
                          onFocus={this.getPayWay}
                          notFoundContent={payWayFetching ? <Spin size="small" /> : messages('pay.key6'/*无匹配结果*/)}
                          disabled={selectFlag}
                          labelInValue>
                    {payWayOptions.map(option => {
                      return <Option key={option.paymentMethodId}>{option.description}</Option>
                    })}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
                {getFieldDecorator('remark', {
                  initialValue: ''
                })(
                  <TextArea autosize={{minRows: 2}} style={{minWidth:'100%'}} placeholder={messages('common.please.input')/*请输入*/}/>
                )}
              </FormItem>
            </Form>
          </Modal>
        ) : (
          <Modal title={messages('pay.key48'/*落地文件重新支付*/)}
                 visible={modalVisible}
                 confirmLoading={modalLoading}
                 footer={[
                   <Button onClick={() => this.setState({modalVisible: false})}>{messages('common.cancel')/*取消*/}</Button>,
                   <DropdownButton
                     overlay={menu}
                     type='primary'
                     placement="bottomRight"
                     onClick={this.handleFileModalOk}
                     disabled={exportLoading}
                     icon={<Icon type="down"/>}
                   >
                     <span>{storageKey === 'file' ? messages('pay.key49')/*导出报盘文件*/ : messages('pay.key220')/*导出报盘明细*/}</span>
                   </DropdownButton>
                 ]}
                 onCancel={() => this.setState({ modalVisible: false })}>
            <Form>
              <div style={{marginBottom:15}}>01. {messages('pay.key50'/*选择付款账号*/)}</div>
              <FormItem  {...formItemLayout} label={messages('pay.key47'/*付款账户*/)}>
                {getFieldDecorator('payCompanyBankNumber', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }]
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}
                          onFocus={this.getPayAccount}
                          notFoundContent={payAccountFetching ? <Spin size="small" /> : messages('pay.key6'/*无匹配结果*/)}
                          onChange={this.selectHandleChange}
                          labelInValue>
                    {payAccountOptions.map(option => {
                      return <Option key={option.companyBank.bankAccountNumber}>
                        {`${option.companyBank.bankAccountName} - ${option.companyBank.bankAccountNumber}`}
                      </Option>
                    })}
                  </Select>
                )}
              </FormItem>
              <FormItem  {...formItemLayout} label={messages('common.currency')/*币种*/} style={{marginBottom:15}}>
                {getFieldDecorator('currency', {
                  rules: [{
                    required: true
                  }],
                  initialValue: currency
                })(
                  <Input disabled />
                )}
              </FormItem>
              <FormItem  {...formItemLayout} label={messages('common.currency.rate')/*汇率*/}>
                {getFieldDecorator('exchangeRate', {
                  rules: [{
                    required: true
                  }]
                })(
                  <Input disabled />
                )}
              </FormItem>
              <div style={{marginBottom:15}}>02. {messages('pay.key51'/*选择付款方式*/)}</div>
              <FormItem  {...formItemLayout} label={messages('pay.key25'/*付款方式*/)}>
                {getFieldDecorator('paymentTypeId', {
                  rules: [{
                    required: true,
                    message: messages('common.select')/*请选择*/
                  }]
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}
                          onFocus={this.getPayWay}
                          notFoundContent={payWayFetching ? <Spin size="small" /> : messages('pay.key6'/*无匹配结果*/)}
                          disabled={selectFlag}
                          labelInValue>
                    {payWayOptions.map(option => {
                      return <Option key={option.paymentMethodId}>{option.description}</Option>
                    })}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/} style={{marginBottom:15}}>
                {getFieldDecorator('description', {
                  initialValue: ''
                })(
                  <TextArea autosize={{minRows: 2}} style={{minWidth:'100%'}} placeholder={messages('common.please.input')/*请输入*/}/>
                )}
              </FormItem>
              <div style={{marginBottom:15}}>03. {messages('pay.key221')/*点击下方【导出报盘文件/明细】按钮*/}</div>
              <div>
                <Row>
                  <Col offset={1} span={23}>1.{messages('pay.key222')/*导出报盘文件/明细后，单据状态变为【支付中】*/}</Col>
                </Row>
                <Row>
                  <Col offset={1} span={23}>2.{messages('pay.key223')/*可通过报盘文件/明细，在网银中进行支付*/}</Col>
                </Row>
                <Row>
                  <Col offset={1} span={23}>3.{messages('pay.key55'/*支付成功后，在【等待付款结果】标签下确认支付状态*/)}</Col>
                </Row>
              </div>
            </Form>
          </Modal>
        )}
        <ErrorModal visible={errorVisible} close={this.handleCloseError} data={errorData}/>
      </Spin>
    )
  }

}

PayFail.contextTypes = {
  router: React.PropTypes.object
};

PayFail.propTypes = {
  subTab: React.PropTypes.string,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

const wrappedPayFail = Form.create()(PayFail);
const WrappedPayFailHoc = CheckModal(wrappedPayFail);
export default connect(mapStateToProps)(WrappedPayFailHoc);
